import 'package:flutter/material.dart';
import '../../manger/network_utils.dart';
import '../../models/user_info_model.dart';
import 'package:flutter_line_sdk/flutter_line_sdk.dart';
import '../../manger/user_manger.dart';
import '../../components/toast_utils.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../controller/auth_bind_view.dart';
import '../../manger/umevent_utils.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
class LoginThirdLoginView extends StatefulWidget {
  final int type;
  final VoidCallback? onThridLoginSuccess;
  const LoginThirdLoginView({super.key, required this.type, this.onThridLoginSuccess});

  @override
  State<LoginThirdLoginView> createState() => _LoginThirdLoginViewState();
}

class _LoginThirdLoginViewState extends State<LoginThirdLoginView> {
  List<String> thridList = [];
  @override
  void initState() {
    super.initState();
    _getUserInfos();
  }

  Future<void> _getUserInfos() async {
    final response = await NetworkUtils.get(
      RequestCmd.oauthconfig,
      params: {'type': widget.type},
    );
    final model = ThreeLoginModel.fromJson(response);
    if (model.code == 200) {
      setState(() {
        thridList = model.data ;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: widget.type == 0 ? BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFFFFFFFF), Color(0xFFF5F5F5)],
        ),
      ) : BoxDecoration(color: Colors.white),
      child: Column(
        children: [
          SizedBox(height: 15),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: thridList.map((item) {
                final prefix = item.split('_')[0];
                return Row(
                  children: [
                    _buildThirdPartyIcon('assets/images/$prefix.png'),
                  ],
                );
              }).toList(),
            ),
          ),
          SizedBox(height: 12),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 15),
            height: 20,
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: Container(
                    height: 1,
                    color: Color(0xFFECECEC),
                    margin: EdgeInsets.only(right: 30),
                  ),
                ),
                Text(
                  'OR',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF999999),
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 1,
                    color: Color(0xFFECECEC),
                    margin: EdgeInsets.only(left: 30),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildThirdPartyIcon(String assetPath) {
    return GestureDetector(
      onTap: () {
        if (assetPath.contains('google')) {
          _signInWithGoogle();
        } else if (assetPath.contains('line')) {
          _lineLogin();
        } else {
          _appleLogin();
        }
      },
      child: Image.asset(
        assetPath,
        width: 55,
        height: 55,
      ),
    );
  }

  Future<void> _signInWithGoogle() async {
    widget.type == 0 ? UmengEvent.trackEvent("login_google_log","登录页选择google三方登录，且点击登录按钮","") : UmengEvent.trackEvent("register_google_reg","注册页选择google三方注册，且点击注册按钮","");
    final GoogleSignIn googleSignIn = GoogleSignIn(
        scopes: [
          'email', // 可选，如果不需要可以移除
          'profile', // 可选，如果不需要可以移除
        ],
    );
    try {
      final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
      if (googleUser != null) {
        final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
        // 获取 Access Token（用于调用 Google API）
        final String? accessToken = googleAuth.accessToken;
        if (accessToken == null) {
        } else {
          _thridLogin(accessToken, 0);
        }
      }
    } catch (error) {
      print('Error signing in: $error');
    }
  }

  Future<void> _lineLogin() async {
    widget.type == 0 ? UmengEvent.trackEvent("login_line_log","登录页选择line三方登录，且点击登录按钮","") : UmengEvent.trackEvent("register_line_reg","注册页选择line三方注册，且点击注册按钮","");
    try {
      final result = await LineSDK.instance.login(
        scopes: ['profile','openid','email'],
      );
      final accessToken = result.accessToken.idTokenRaw;
      if (accessToken == null) {
        return;
      } else {
        _thridLogin(accessToken, 1);
      }

    } catch (e) {
      print('Line 登录失败: $e');
    }
  }

  Future<void> _appleLogin() async {
    widget.type == 0 ? UmengEvent.trackEvent("login_apple_log","登录页选择apple三方登录，且点击登录按钮","") : UmengEvent.trackEvent("register_apple_reg","注册页选择apple三方注册，且点击注册按钮","");
      try {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.fullName,
        AppleIDAuthorizationScopes.email,
      ],
    );

    // 你可以拿到 credential.identityToken / authorizationCode 传给后台校验
    final identityToken = credential.identityToken;

    if (identityToken == null) {
      return;
    } else {
      _thridLogin(identityToken, 2);
    }

    // TODO: 调用你们后台 API 进行 Apple 登录/注册绑定
    } catch (e) {
      print("🍎 Apple 登录失败: $e");
    }
  }

  Future<void> _thridLogin(String token,int type) async {
    if (mounted) {
      ToastUtils.showLoadingToast(context);
    }
    // print('token info: $token');
    try {
      final response = await NetworkUtils.post(
        RequestCmd.authorizelogin,
        body: {"loginType":type,"code":token},
      );

      ToastUtils.dismissLoadingToast();
      if (response.toString().contains('804')) {
        final model = UserBingData.fromJson(response);
        if (model.data != null) {
          pushAutn(model.data,type);
          return;
        } else {
          ToastUtils.showCenterToast(context, model.msg);
          return;
        }

      } else {
        final model = LoginModel.fromJson(response);
        if (model.code == 200) {
          if (model.data?.model != null) {
            final tokenModel = model.data!.model!;
            UserInfos.shared.saveToken(tokenModel.accessToken);
            widget.onThridLoginSuccess?.call();
          } else if (model.data?.boolValue != null) {
            // 处理bool情况
            final boolValue = model.data!.boolValue!;
            // 这里添加处理布尔值的逻辑
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '登录失败,请联系客服');
        }
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    }
  }

  void pushAutn(UsssBingInfo? bingInfo,int type) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AuthBindView(loginType: type, bingInfo: bingInfo),
      ),
    );
  }
}